<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * P卡申请管理
 *
 * @icon fa fa-circle-o
 */
class Virtualmachinepcardapply extends Backend
{
    
    /**
     * Virtualmachinepcardapply模型对象
     * @var \app\admin\model\Virtualmachinepcardapply
     */
    protected $model = null;
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'admin_id';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Virtualmachinepcardapply;
        $this->view->assign("statusList", $this->model->getStatusList());
        $virtualmachine = $this->request->param('virtualmachine');
        $this->assignconfig('virtualmachine', $virtualmachine);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
            if($lists){
                foreach ($lists as $k=>$v){
                    $admin = Db::name('admin')->where('id', '=', $v['admin_id'])->find();
                    if($admin){
                        $lists[$k]['admin_name'] = $admin['nickname'];
                    }else{
                        $lists[$k]['admin_name'] = '管理员已删除';
                    }
                     $account = Db::name('fedition_account')->where('id', '=', $v['virtualmachine'])->find();
                    if($account){
                        $lists[$k]['virtualmachine_name'] = $account['email'];
//                        $lists[$k]['ip'] = $account['ip'];
//                        $lists[$k]['ippassword'] = $account['ippassword'];
//                        $lists[$k]['email'] = $account['email'];
//                        $lists[$k]['emailpassword'] = $account['emailpassword'];
                    }else{
                        $lists[$k]['virtualmachine_name'] = '账户已删除';
//                        $lists[$k]['ip'] = '';
//                        $lists[$k]['ippassword'] = '';
//                        $lists[$k]['email'] = '';
//                        $lists[$k]['emailpassword'] = '';
                    }
                }
            }

            $Statistics['znum'] = $this->model
                ->where($where)
                ->count();
            $Statistics['ztoday'] = $this->model
                ->where($where)
                ->where('createtime','>',strtotime('today'))
                ->count();
            $Statistics['nohandle'] = $this->model
                ->where($where)
                ->where('createtime','>',strtotime('today'))
                ->where('status','hidden')
                ->count();
            $result = array("total" => $list->total(), "rows" => $lists, "Statistics" => $Statistics);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();

                $account = Db::name('fedition_account')->where('id',$params['virtualmachine'])->where('ispcard',0)->find();
                if (!empty($account)) {
                    //状态改成申请中
                    $arr['ispcard'] = 2;
                    Db::name('fedition_account')->where('id',$params['virtualmachine'])->where('ispcard',0)->update($arr);
                } else {
                    $this->error('绑卡状态不正确请检查');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['admin_id'] = $this->auth->id;
                    $params['createtime'] = time();
                    $params['updatetime'] = time();
                    $result = $this->model->allowField(true)->insertGetId($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //type 类型 operation具体操作
                    $this->add_pcardlog_log(2,$result,1);
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $virtualmachine = $this->request->param('virtualmachine');
        if (empty($virtualmachine)) {
            $virtualmachine = '';
        }
        $this->view->assign("virtualmachine", $virtualmachine);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $account = Db::name('fedition_account')->where('id',$row['virtualmachine'])->find();
        if (empty($account)) {
            $this->error(__('账户不能为空'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();

//                判断开始
                $oldstatus = $row['status'];
                $admin_id = $row['admin_id'];
                //拒绝后回退申请
                if($params['status'] == 'refuse') {
                    //更改账户
                    $arr['ispcard'] = 0;
                    $arr['pcard_id'] = 0;
                    $account = Db::name('fedition_account')->where('id',$row['virtualmachine'])->update($arr);
                    $this->add_virtualmachine_log(5,$row['virtualmachine'],3);
                    //更改P卡账户
                    $arr_pcard['status'] = 'notused';
                    $arr_pcard['usetime'] = '';
                    $arr_pcard['virtualmachine'] = '';
                    Db::name('virtualmachine_pcard')->where('id',$params['pcard'])->update($arr_pcard);
                    $this->add_pcardlog_log(2,$ids,4);
                } else {
                    if ($row['status'] == 'normal') {
                        $this->error(__('P卡已申请通过，无法修改'));
                    }
                    //判断账户是否已被通过申请
                    if (empty($row['virtualmachine'])) {
                        $this->error(__('申请账户不能为空'));
                    }
                    if (empty($params['pcard'])) {
                        $this->error(__('绑定P卡账户不能为空'));
                    }
//type 类型 operation具体操作
                    if ($oldstatus !== 'normal' && $params['status'] == 'normal') {
                        $params['passingtime'] = time();
                        //判断P卡
                        $virtualmachine_pcard = Db::name('virtualmachine_pcard')->where('id',$params['pcard'])->where('status','notused')->find();
                        if (empty($virtualmachine_pcard)) {
                            $this->error(__('P卡不是未使用状态，请重试'));
                        }
                        //更改账户
                        $accountinfo = Db::name('fedition_account')->where('id',$row['virtualmachine'])->find();
                        if (empty($accountinfo)) {
                            $this->error(__('账户已绑定P卡，无需重复申请'));
                        } else {
                            $arr['ispcard'] = 1;
                            $arr['pcard_id'] = $params['pcard'];
                            $account = Db::name('fedition_account')->where('id',$row['virtualmachine'])->update($arr);
                            if (!empty($account)) {
                                $this->add_virtualmachine_log(5,$row['virtualmachine'],1);
                            } else {
                                $this->add_virtualmachine_log(5,$row['virtualmachine'],2);
                            }
                        }
                        //更改P卡账户
                        $arr_pcard['status'] = 'normal';
                        $arr_pcard['usetime'] = time();
                        $arr_pcard['virtualmachine'] = $row['virtualmachine'];
                        Db::name('virtualmachine_pcard')->where('id',$params['pcard'])->where('status','notused')->update($arr_pcard);
                    }else{
                        $this->add_pcardlog_log(2,$ids,2);
                    }
                }

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("account", $account);
        return $this->view->fetch();
    }

}
